package com.hqx.gulimall.product.service.impl;

import com.hqx.common.utils.PageUtils;
import com.hqx.common.utils.Query;
import com.hqx.gulimall.product.dao.ProductAttrValueDao;
import com.hqx.gulimall.product.entity.ProductAttrValueEntity;
import com.hqx.gulimall.product.service.ProductAttrValueService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveProductAttr(List<ProductAttrValueEntity> collect) {
        this.saveBatch(collect);
    }

    @Override
    public List<ProductAttrValueEntity> getBaseAttrListForSpu(Long spuId) {
        return this.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));
    }

    @Override
    @Transactional
    public void updateBaseAttrForSpu(Long spuId, List<ProductAttrValueEntity> productAttrValueEntities) {
        // 先删除spuId对应的所有数据(有些属性之前没录入更新其实是插入操作，之前录入的属性才是更新操作，所以这里先删除，然后统一做插入操作)
        this.remove(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));

        if(!productAttrValueEntities.isEmpty()) {
            List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueEntities.stream().peek(item -> item.setSpuId(spuId)).collect(Collectors.toList());
            this.saveBatch(productAttrValueEntityList);
        }
    }

}